package com.example.springalibabacloudfeign.config;


import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Classname FeignClientInterceptor
 * @Description TODO
 * @Date 2022/3/22 23:45
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@Slf4j
@Component
public class FeignClientInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {

        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();


        //拦截器
        //使用RequestContextHolder工具获取request相关变量
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

            if (attributes != null){

//            取出request
                HttpServletRequest request = attributes.getRequest();

//                取出所有请求头
                Enumeration<String> headerNames = request.getHeaderNames();
                while (headerNames.hasMoreElements()){
                    String name = headerNames.nextElement();   // key
                    String value = request.getHeader(name);   //value
                    requestTemplate.header("Authorization","Bearer 676e5808-6f05-4aa1-9f8a-86f39c10d45b");
                   requestTemplate.header("keyww","helloword");

                }
            }

            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
//                取出所有请求头
            System.out.println("==================================>1111");
            System.out.println(request.getRequestURL());
            while (headerNames.hasMoreElements()){
                String name = headerNames.nextElement();   // key
                String value = request.getHeader(name);   //value
                System.out.println(name+"  "+value);
            }

        }catch (Exception e){
        }
    }

}
